package com.biao.mall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class FeignConfig {

    /**
     * feign远程调用时候不会携带上任何cookie数据
     * 需要给template模板添加上需要的header信息
     */
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        return template -> {
            //1.RequestContextHolder拿到request请求(通过threadLocal)
            //当前线程
            //从线程池中的线程是不共享threadLocal的需要在异步任务中重新设置 attributes
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes==null){
                return;
            }
            HttpServletRequest request = attributes.getRequest();//旧请求
            //2.同步请求头信息Cookie
            String cookie = request.getHeader("Cookie");
            //给新请求同步cookie
            template.header("Cookie", cookie);
            //System.out.println("feign远程之前先进行requestInterceptor()");
        };
    }
}
